import { blackRouter, constantRoutes } from '@/router'

const getDefaultState = () => {
  return {
    menus: []
  }
}
const filterMenus = (menus, menuIds) => {
  const type = Object.prototype.toString.call(menus)
  if (type === '[object Array]') {
    menus.forEach((v) => {
      filterMenus(v, menuIds)
    })
  } else if (type === '[object Object]') {
    if (menus.children && menus.children.length) {
      menus.children.forEach((v) => {
        filterMenus(v, menuIds)
      })
    }
  }
  if (menus.menuId) {
    if (menuIds.indexOf(`${menus.menuId}`) === -1) {
      menus.hidden = true
    }
  }
  return menus
}
const state = getDefaultState()

const mutations = {
  SET_MENUS: (state, menus) => {
    state.menus = menus
  }
}

const actions = {
  // 设置动态权限菜单
  setMenus({ commit }, menuIds) {
    const serverMenus = filterMenus(blackRouter, menuIds)
    commit('SET_MENUS', [...constantRoutes, ...serverMenus])
  },
  clearMenus({ commit }) {
    commit('SET_MENUS', [...constantRoutes])
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

